package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pchavez on 17/01/14.
 */
public class Repository {
    private List<Borrowable> borrowables;


    public Repository(List<Borrowable> borrowables) {
        this.borrowables = borrowables;
    }

    public boolean checkOut(String title, User user) {
        Borrowable borrowableToCheckOut = getBorrowable(title);
        if(borrowableToCheckOut == null || borrowableToCheckOut.canBeCheckedOut() == false){
            return false;
        }
        checkInOrCheckOutBook(title, false);
        user.addBorrowable(borrowableToCheckOut);
        return true;
    }

    public boolean checkIn(String title, User user) {
        Borrowable borrowableToCheckIn = getBorrowable(title);
        if(borrowableToCheckIn == null || borrowableToCheckIn.canBeCheckedIn() == false) {
            return false;
        }

        checkInOrCheckOutBook(title, true);
        user.removeBorrowable(borrowableToCheckIn);
        return true;
    }

    private void checkInOrCheckOutBook(String title, Boolean checkIn){
        Borrowable borrowable = getBorrowable(title);
        if (checkIn == true){
            borrowable.checkIn();
        }else{
            borrowable.checkOut();
        }
    }

    private Borrowable getBorrowable(String title){
        for(Borrowable borrowable : borrowables){
            if(borrowable.getTitle().equals(title)){
                return borrowable;
            }
        }
        return null;
    }

    public List<Borrowable> getAvailableBookList() {
       return getAvailableBorrowables("book");
    }


    public List<Borrowable> getAvailableMovieList() {
        return getAvailableBorrowables("movie");
    }

    private List<Borrowable> getAvailableBorrowables(String borrowableType) {
        List<Borrowable> availableBorrowablesList = new ArrayList<Borrowable>();
        for(Borrowable borrowable : borrowables){
            if (borrowable.canBeCheckedOut() && borrowable.getType().equals(borrowableType)){
                availableBorrowablesList.add(borrowable);
            }
        }
        return availableBorrowablesList;
    }
}



